#version 330 core

struct Material {
    sampler2D diffuse;
    sampler2D specular;
    sampler2D emission;
    float shininess;
};

struct Light {
    vec3 position;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

out vec4 FragColor;

in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;

uniform vec3 viewPos;
uniform Material material;
uniform Light light;
// 时间统一变量，用于控制流动速度
uniform float u_time;

void main()
{
    // 环境光
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));

    // 漫反射 
    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(light.position - FragPos);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));

    // 镜面光
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 reflectDir = reflect(-lightDir, norm);  
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));

    // 定义流动速度
    float flowSpeed = 0.1;
    // 计算垂直方向的偏移量，使用 fract 函数确保偏移在 [0, 1] 范围内
    float verticalOffset = fract(TexCoords.y + u_time * flowSpeed);
    // 创建修改后的纹理坐标，x 坐标不变，y 坐标加上偏移量
    vec2 newTexCoords = vec2(TexCoords.x, verticalOffset);

    // 自发光
    vec3 emission = vec3(0.f);
    // 限制范围
    if (TexCoords.y >= 0.1 && TexCoords.y <= 0.9 && TexCoords.x >= 0.1 && TexCoords.x <= 0.9)
    {
        emission = vec3(texture(material.emission, newTexCoords));
    }

    vec3 result = ambient + diffuse + specular + emission;
    FragColor = vec4(result, 1.0);
}